<template>
  <div class="task-detail-footer">
    <h2 v-if="props.project?.projectName">
      <el-icon><CollectionTag /></el-icon> 项目名称
    </h2>
    <div class="p" v-if="props.project?.projectName">
      {{ props.project?.projectName }}
    </div>

    <h2 v-if="props.project?.projectDescribe">
      <el-icon><Postcard /></el-icon> 项目描述
    </h2>
    <div class="md" v-if="props.project?.projectDescribe">
      <wageditor-readonly :projectDescribe="props.project?.projectDescribe"></wageditor-readonly>
    </div>

    <h2 v-if="props.task.taskSkill">
      <el-icon><Aim /></el-icon> 技能需求
    </h2>
    <div class="p" v-if="props.task.taskSkill">
      {{ props.task.taskSkill }}
    </div>

    <h2 v-if="props.task.taskRequire">
      <el-icon><Tickets /></el-icon> 任务描述
    </h2>
    <div class="md" v-if="props.task.taskRequire">
      <wageditor-readonly :projectDescribe="props.task.taskRequire"></wageditor-readonly>
    </div>

    <h2 v-if="props.project?.phoneNumber">
      <el-icon><Phone /></el-icon> 联系方式
    </h2>
    <div class="p" v-if="props.project?.phoneNumber">
      {{ props.project?.phoneNumber }}
    </div>

    <h2 v-if="props.project?.modelVOS">
      <el-icon><MessageBox /></el-icon> 模块分解
    </h2>
    <div class="contact">
      <functional-decomposition :project="props.project" :showButton="showButton" />
    </div>

    <h2>
      <el-icon><Folder /></el-icon> 相关附件
    </h2>
    <div class="attachments">
      <el-button @click="downloadTaskFile">下载任务附件</el-button>
      <el-table
        :data="displayedFileList"
        height="250"
        v-if="props.task.taskState === 2 || props.task.taskState === 3"
      >
        <el-table-column fixed prop="name" label="任务实施附件（实施人员上传）" />
        <el-table-column width="180">
          <template #default="scope">
            <el-button type="primary" plain size="small" @click="downloadFile(scope.row)"
              >下载</el-button
            >
            <el-button type="danger" plain size="small" @click="deleteFile(scope.row, scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-upload
        v-if="
          props.task.taskState === 2 &&
          props.task.taskOrderTaker == useUserStore().userMessage.userId
        "
        class="upload"
        drag
        :before-upload="beforeUpload"
        :http-request="handleUpload"
      >
        <div class="el-upload__text">将文件拖到此处，或<em>点此上传</em></div>
        <template #tip>
          <div class="el-upload__tip">上传文件不能超过5MB</div>
        </template>
      </el-upload>
    </div>

    <h2 v-if="props.task.taskBid && props.task.taskState === 1">
      <el-icon><Flag /></el-icon> 投标情况
    </h2>
    <div class="taskBid" v-if="props.task.taskBid && props.task.taskState === 1">
      <div v-for="(item, index) in usersIdList" :key="index">
        <users-list-items
          :userId="item"
          :task="props.task"
          :project="props.project"
          @updateTask="handleTaskUpdate"
        ></users-list-items>
      </div>
    </div>

    <h2 v-if="props.task.taskState === 2">
      <el-icon><Flag /></el-icon> 实施人员
    </h2>
    <div class="taskBid" v-if="props.task.taskState === 2">
      <div>
        <users-list-items
          :userId="props.task.taskOrderTaker"
          :task="props.task"
          :project="props.project"
          @updateTask="handleTaskUpdate"
        ></users-list-items>
      </div>
    </div>

    <h2 v-if="props.task.taskState === 2">
      <el-icon><Operation /></el-icon> 任务进度
    </h2>
    <div class="progress" v-if="props.task.taskState === 2">
      <van-slider
        class="no-select"
        v-model="tempPercent"
        :step="10"
        bar-height="8px"
        button-size="20px"
        style="width: 800px"
        v-if="props.task.taskOrderTaker == useUserStore().userMessage.userId"
      >
        <template #button>
          <div class="custom-button">{{ tempPercent + '%' }}</div>
        </template>
      </van-slider>
      <el-button
        type="success"
        :icon="Check"
        circle
        :disabled="isButtonDisabled"
        @click="taskUpdate"
        v-if="props.task.taskOrderTaker == useUserStore().userMessage.userId"
      />
      <van-slider
        class="no-select"
        v-model="tempPercent"
        readonly
        :step="10"
        bar-height="8px"
        button-size="20px"
        style="width: 800px"
        v-if="projectUserId === useUserStore().userMessage.userId"
      >
        <template #button>
          <div class="custom-button">{{ tempPercent + '%' }}</div>
        </template>
      </van-slider>
    </div>
    <div class="btn" v-if="props.task.taskState === 2">
      <el-button
        type="primary"
        plain
        @click="taskSubmit"
        v-if="props.task.taskOrderTaker == useUserStore().userMessage.userId"
        >提交任务</el-button
      >
      <el-button
        type="primary"
        plain
        @click="confirmAcceptance"
        v-if="
          projectUserId === useUserStore().userMessage.userId && props.task.taskProgress === 100
        "
        >验收任务</el-button
      >
      <el-button
        type="danger"
        plain
        @click="cancelAcceptance"
        v-if="
          projectUserId === useUserStore().userMessage.userId && props.task.taskProgress === 100
        "
        >打回任务</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import functionalDecomposition from '@/components/functional-decomposition/functional-decomposition.vue'
import { ref, onMounted, watch, computed } from 'vue'
import UsersListItems from './users-list-items.vue'
import useUserStore from '@/store/user/user'
import { acceptTask, getTaskDetail } from '@/service/taskdetail/taskdetail'
import { getProject } from '@/service/project/project'
import { upLoadFile } from '@/service/user/user'
import { Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import wageditorReadonly from '@/components/wageditor/wageditorReadonly.vue'
const emit = defineEmits(['updateTask', 'updateFile', 'updateProgress'])
const props = defineProps(['task', 'project'])
const showButton = ref(false)
const tempFile = ref(props.task.file)
const downloadTaskFile = () => {
  window.location.href = fileList.value[0].url
}
const downloadFile = (row: any) => {
  window.location.href = row.url
}
const deleteFile = (row: any, index: number) => {
  ElMessageBox.confirm(`确定删除${row.name}吗?`, '删除附件')
    .then(() => {
      try {
        let temporaryList = [...fileList.value]
        temporaryList.splice(index + 1, 1)
        tempFile.value = temporaryList.map((file) => file.url).join('|')
        emit('updateFile', tempFile.value)
        ElMessage.success('删除成功')
        parseFileList()
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}
interface FileItem {
  name: string
  url: string
}
const fileList = ref<FileItem[]>([])
const parseFileList = () => {
  if (props.task.file) {
    //如果file不存在|，则只有任务附件
    if (!props.task.file.includes('|')) {
      const parts = props.task.file.split('*')
      fileList.value = [{ name: parts[1], url: props.task.file }]
    } else {
      const files = props.task.file.split('|')
      fileList.value = files.map((file: any) => {
        const parts = file.split('*')
        return { name: parts[1], url: file }
      })
    }
    console.log('fileList:', fileList.value)
  }
}
// 文件上传之前的检查
function beforeUpload(file: any) {
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过 5MB')
  }
  return isLt5M
}
// 处理文件上传
function handleUpload(request: any) {
  const formData = new FormData()
  formData.append('file', request.file)
  return upLoadFile(formData).then((response: any) => {
    if (response.code === 1) {
      ElMessage.success('上传成功')
      emit('updateFile', (tempFile.value += `|${response.data}`))
      parseFileList()
    } else {
      ElMessage.error('上传失败')
    }
  })
}
const usersIdList = ref([])
const displayedFileList = computed(() => fileList.value.slice(1))
const handleTaskUpdate = (userId: string) => {
  emit('updateTask', userId)
}
onMounted(() => {
  if (props.task.taskBid) {
    usersIdList.value = props.task.taskBid.split(',')
  }
})

watch(
  () => props.task.taskBid,
  (newVal) => {
    usersIdList.value = newVal ? newVal.split(',') : []
  }
)
const tempPercent = ref(props.task.taskProgress) || 0
const isButtonDisabled = computed(() => {
  return tempPercent.value === props.task.taskProgress
})
const taskUpdate = () => {
  if (tempPercent.value === 100) {
    taskSubmit()
  } else {
    emit('updateProgress', tempPercent.value)
    ElMessage.success('任务进度更新成功')
  }
}
const taskSubmit = () => {
  ElMessageBox.confirm(`确定提交任务吗?`, '任务进度调整到100%')
    .then(async () => {
      try {
        tempPercent.value = 100
        emit('updateProgress', tempPercent.value)
        ElMessage.success('提交成功')
      } catch (error) {
        ElMessage.error('提交失败')
      }
    })
    .catch(() => {
      ElMessage.info('取消提交')
    })
}
const confirmAcceptance = () => {
  ElMessageBox.confirm(`确定验收任务吗?`, '任务进度达到100%')
    .then(async () => {
      try {
        await acceptTask(props.task.taskId)
        location.reload()
        ElMessage.success('验收成功')
      } catch (error) {
        ElMessage.error('验收失败')
      }
    })
    .catch(() => {
      ElMessage.info('取消验收')
    })
}
const cancelAcceptance = () => {
  ElMessageBox.confirm(`确定打回任务吗?`, '实施人员需重新提交任务')
    .then(async () => {
      try {
        tempPercent.value = 90
        emit('updateProgress', tempPercent.value)
        ElMessage.success('打回成功')
      } catch (error) {
        ElMessage.error('打回失败')
      }
    })
    .catch(() => {
      ElMessage.info('取消打回')
    })
}
const projectUserId = ref()
const fetchTaskDetail = async () => {
  const taskResponse = await getTaskDetail(props.task.taskId)
  const projectResponse = await getProject(taskResponse.data.projectsId)
  projectUserId.value = projectResponse.data.userId
}
onMounted(() => {
  fetchTaskDetail()
  parseFileList()
})
</script>

<style lang="less" scoped>
h2 {
  font-size: 18px;
  margin: 10px;
}
.p {
  margin: 10px 40px;
}
.md {
  margin: 10px 40px;
  border: #dcdfe6 1px solid;
  border-radius: 10px;
  padding: 0 10px;
}
.contact {
  margin: 10px 40px;
  border: #dcdfe6 1px solid;
  border-radius: 10px;
  padding: 10px;
}
.attachments {
  margin: 10px 40px;
  .el-table {
    border: #dcdfe6 1px solid;
    border-radius: 10px;
    margin: 10px 0;
    overflow-x: hidden;
  }
}
.taskBid {
  border: #dcdfe6 1px solid;
  margin: 10px 40px;
  border-radius: 10px;
  padding: 0 10px;
}
.progress {
  margin: 10px 40px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .no-select {
    user-select: none;
  }
  .custom-button {
    width: 26px;
    color: #fff;
    font-size: 10px;
    line-height: 18px;
    text-align: center;
    background-color: var(--van-primary-color);
    border-radius: 100px;
  }
}
.btn {
  margin: 10px 40px;
}
</style>
